import WebSocket, { WebSocketServer } from "ws";
// Bug fix: Correct the import path to '../db.js'
import { query } from '../db.js';

export default class WebSocketServerClass {
  constructor(httpServer) {
    this.clients = {};
    this.clientNum = 0;

    // 创建 WebSocket 服务器，并将其与 HTTP 服务器关联
    this.wss = new WebSocketServer({ server: httpServer });
    // 监听的是 WebSocket 服务开始监听的事件
    this.wss.on("listening", (socket) => {
      console.log("web socket begins listening");
    });

    // WebSocket 服务被客户端连接上的事件
    this.wss.on("connection", (client, req) => {
      console.log("New WebSocket client connected");
      //给客户端编号,也就是参与聊天的用户
      client.name = ++this.clientNum;
      this.clients[client.name] = client;

      client.on("message", (message) => {
          try {
              const data = JSON.parse(message.toString());
              if (data.type === 'register' && data.clientId) {
                  // 使用客户端自定义ID
                  client.name = data.clientId;
                  this.clients[client.name] = client;
                  client.send(JSON.stringify({
                      type: 'system',
                      message: `注册成功，你的ID: ${client.name}`
                  }));
              } else {
                  // 正常消息处理
                  this.onMessage(message, client);
              }
          } catch (error) {
              console.error('消息解析失败:', error);
          }
      });
      client.on("close", this.onClose);
      client.on("error", this.onError);

      const ip = req.connection.remoteAddress;
      console.log(ip + " is connected");
      client.send("message from server: hi");
    });
  }

  async onMessage(message, ws) {
    try {
      // 将 Buffer 转换为字符串后再解析为对象
      const data = JSON.parse(message.toString());  // <-- 添加 Buffer 转换
      const { latitude, longitude, deviceInfo } = data;
      if(!latitude || !longitude || !deviceInfo) {
        console.log('Invalid data received:', data);
        return;
      }

      let sql;
      let values;
      if (process.env.DB_TYPE === 'postgres') {
        sql = `
          INSERT INTO location_data (latitude, longitude, device_info)
          VALUES ($1, $2, $3)
        `;
        values = [latitude, longitude, deviceInfo];
      } else if (process.env.DB_TYPE === 'mysql') {
        sql = `
          INSERT INTO location_data (latitude, longitude, device_info)
          VALUES (?, ?, ?)
        `;
        values = [latitude, longitude, deviceInfo];
      }

      // await query(sql, values);

      console.log(`Received message: ${message}`);
      ws.send(`Server received: ${message}`);
    } catch (error) {
      console.error('Error processing message:', error);
    }
  }

  // 服务端收到了客户端关闭连接的事件，由客户端发起的关闭
  onClose() {
    console.log("WebSocket client disconnected");
  }

  // WebSocket 通信过程中出错的事件
  onError(error) {
    console.log("error:", error);
  }
}
